﻿using System;
using System.Collections.Generic;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using Phoenix.Xna.Framework.Collections;

namespace Phoenix.Xna.Framework.Components.Compositors
{
    public class MiniMap : ImageCompositor
    {
        private string _markerAsset;
        private Texture2D _marker;

        public MultiMap<Color, I3DComponent> Components { get; set; }
        public Vector2 MapScale { get; set; }

        public MiniMap(string map, string marker)
            : base(map)
        {
            Components = new MultiMap<Color, I3DComponent>();
            _markerAsset = marker;
        }

        public MiniMap(string id, string map, string marker)
            : base(id, map)
        {
            Components = new MultiMap<Color, I3DComponent>();
            _markerAsset = marker;
        }

        #region IDrawableComponent Members

        public override void LoadContent()
        {
            if (!IsContentLoaded)
            {
                _marker = Engine.Instance.Content.Load<Texture2D>(_markerAsset);
                base.LoadContent();
            }
        }

        public override void UnloadContent()
        {
            if (IsContentLoaded)
            {
                Engine.Instance.Content.Release(_markerAsset);
                base.UnloadContent();
            }
        }

        public override void Draw(Microsoft.Xna.Framework.GameTime gameTime)
        {
            base.Draw(gameTime);

            foreach (KeyValuePair<Color, List<I3DComponent>> p in Components)
            {
                Vector2 imageCenter = new Vector2(_marker.Width / 2, _marker.Height / 2);

                foreach (I3DComponent c in p.Value)
                {
                    int left = (int)(Math.Abs((c.Position.X / MapScale.X) % Image.Width) * Scale.X);
                    int top = (int)(Math.Abs((c.Position.Z / MapScale.X) % Image.Height) * Scale.Y);
                    SpriteBatch.Draw(_marker,
                        new Vector2((left + Position.X) - imageCenter.X,
                            (top + Position.Y) - imageCenter.Y),
                        SourceRectangle,
                        p.Key,
                        Rotation,
                        Origin,
                        Vector2.One,
                        Effect,
                        LayerDepth);
                }
            }
        }

        #endregion
    }
}
